import os
import uuid
import json
import logging
from flask import Flask, request, Response, jsonify
from searcher import Searcher
from celery_task.build_index.tasks import build_index_all


def success(message='操作成功', sort=True, **kwargs):
    data = dict(message=message, error_code=0, success=True, data={})
    for r in list(kwargs.keys()):
        data[r] = kwargs.get(r)
    if not sort:
        return Response(json.dumps(data), mimetype='application/json')
    return jsonify(data)


def error(message='操作失败', error_code=1, **kwargs):
    data = dict(message=message, error_code=error_code, success=False, data={})
    for r in list(kwargs.keys()):
        data[r] = kwargs.get(r)
    return jsonify(data)


app = Flask(__name__)


@app.route('/get_path', methods=['POST', 'GET', 'PUT', 'DELETE'])
def get_path():
    if request.method != 'POST':
        return error(message='request method must be POST')
    keyword = request.json.get('keyword')
    if not keyword:
        return error(message='please provide keyword')
    searcher = Searcher()
    path_list = searcher.search_documents(keyword)
    if path_list:
        path_list = path_list[0].split(';')
    return success(data={'path_list': path_list})


@app.route('/build_index_all', methods=['POST', 'GET', 'PUT', 'DELETE'])
def build_index_all_():
    if request.method != 'POST':
        return error(message='request method must be POST')
    with open('config.json', 'r') as f:
        data = json.load(f)
    if data.get('building_index', 0):
        return error(message='An index building process already exists')
    path = data.get("monitor_path", "./marked_files/")
    data['building_index'] = 1
    build_index_all.delay(path)
    with open('config.json', 'w') as f:
        json.dump(data, f, indent=4)
    return success(message='Successfully start building index')


@app.route('/build_index_all_status', methods=['POST', 'GET', 'PUT', 'DELETE'])
def build_index_all_status():
    if request.method != 'GET':
        return error(message='request method must be GET')
    with open('config.json', 'r') as f:
        data = json.load(f)
    if data.get('building_index'):
        return success(message='Is building index')
    return success(message='No building index')


if __name__ == '__main__':
    with open('config.json', 'r') as file:
        config = json.load(file)
    if not config.get('is_first', 1):
        print('######################')
        print('首次运行，建议调用/build_index_all接口，为全部文档创建索引')
        print('######################')
        config["is_first"] = 1
        with open('config.json', 'w') as file:
            json.dump(config, file, indent=4)

    app.run(debug=False, host='0.0.0.0', port=5000)
